<template>
  <div id="addActives">
    <el-row type="flex" justiify="center">
      <el-col :span="12" :offset="0">
        <h1 class="con-right-title">转介绍活动</h1>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="22" :offset="1">
        <el-form
          ref="activityInfo"
          label-width="150px"
          :model="activityInfo"
          :rules="activityInfoRules"
        >
          <el-form-item label="活动名称" prop="activityName">
            <el-input
              class="activity-input"
              type="text"
              size="small"
              :maxlength="15"
              show-word-limit
              @change="changeName"
              :disabled="isEditDisalbed"
              :clearable="true"
              v-model.trim="activityInfo.activityName"
            ></el-input>
          </el-form-item>
          <el-form-item label="活动备注" prop="remark">
            <el-input
              class="activity-input"
              type="text"
              size="small"
              show-word-limit
              :clearable="true"
              :disabled="isEditDisalbed"
              v-model.trim="activityInfo.remark"
            ></el-input>
          </el-form-item>
          <el-form-item label="活动起始时间" prop="activityTime">
            <el-date-picker
              v-model="activityInfo.activityTime"
              type="datetimerange"
              :disabled="isEditDisalbed"
              size="small"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="领取奖品时间" prop="acceptThePrizeTime">
            <el-date-picker
              v-model="activityInfo.acceptThePrizeTime"
              type="datetimerange"
              :disabled="isEditDisalbed"
              size="small"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="入量区间设置" prop="enterAmountTime">
            <el-date-picker
              v-model="activityInfo.enterAmountTime"
              type="datetimerange"
              :disabled="isEditDisalbed"
              size="small"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="成单区间设置" prop="activitySucceedTime">
            <el-date-picker
              v-model="activityInfo.activitySucceedTime"
              type="datetimerange"
              :disabled="isEditDisalbed"
              size="small"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="活动封面" prop="activityConver">
            <uploadSingImg
              :imgUrl="activityInfo.activityConver"
              accept=".jpg,.jpeg,.png,.gif"
              :maxSize="0.5"
              @getImgUrl="getActivityConver"
            >
              <template v-slot:imgInfo>
                <span>注：640*320像素，支持PNG、JPG格式，小于500KB</span>
              </template>
            </uploadSingImg>
          </el-form-item>
          <el-form-item label="活动海报" prop="activityPoster">
            <uploadSingImg
              :imgUrl="activityInfo.activityPoster"
              accept=".jpg,.jpeg,.png,.gif"
              :maxSize="5"
              @getImgUrl="getActivePoster"
            >
              <template v-slot:imgInfo>
                <span
                  >（建议上传图片尺寸宽750，高度不限，支持gif，尺寸最大5M）</span
                >
              </template>
            </uploadSingImg>
          </el-form-item>
        </el-form>
        <!-- 活动梯队奖励 -->
        <el-form label-width="150px" ref="ladderForm">
          <el-form-item label="活动奖品"> </el-form-item>
          <div class="section-prize">
            <el-button
              type="primary"
              class="add-section"
              size="medium"
              @click="addSection"
              :disabled="isEditDisalbed"
              >新增</el-button
            >
            <template v-if="activityPrize.length">
              <div class="section-header">
                <div class="section-index"></div>
                <div class="section-num">人数区间</div>
                <div class="prize-name">奖品名称</div>
                <div class="prize-pic">奖品图片</div>
              </div>
              <div
                class="section-wrap"
                v-for="(sectionData, index) in activityPrize"
                :key="index"
              >
                <div class="section-index">{{ index + 1 }}</div>
                <div class="section-num">
                  <el-input
                    v-model.number="sectionData.minPersonNum"
                    class="num-input"
                    :disabled="isEditDisalbed"
                  ></el-input>
                  -
                  <el-input
                    v-model.number="sectionData.maxPersonNum"
                    class="num-input"
                    :disabled="isEditDisalbed"
                  ></el-input>
                </div>
                <div>
                  <template v-for="(prizeData, i) in sectionData.prize">
                    <div class="prize-wrap" :key="i">
                      <div class="prize-name">
                        <el-input
                          v-model.trim="prizeData.prizeName"
                          :disabled="isEditDisalbed"
                          class="num-input"
                        ></el-input>
                        <span style="color: red">建议8字以内</span>
                      </div>
                      <div class="prize-pic">
                        <uploadSmallImg
                          :index="index"
                          :i="i"
                          :imgUrl="prizeData.prizeImg"
                          accept=".jpg,.jpeg,.png,.gif"
                          :maxSize="5"
                          @getImgUrl="getPrizePoster"
                          :isSmallbox="true"
                        >
                          <template v-slot:imgInfo>
                            <span>（建议尺寸 180*180）</span>
                          </template>
                        </uploadSmallImg>
                      </div>
                      <div
                        style="text-align: left;width:150px"
                        v-if="showPrizeBtn(sectionData, i)"
                      >
                        <el-button
                          v-if="i > 0"
                          style="height: 32px; margin-left: 10px"
                          size="small"
                          type="danger"
                          icon="el-icon-delete"
                          @click="delPrize(index, i)"
                          :disabled="isEditDisalbed"
                          >删除</el-button
                        >
                        <el-button
                          v-if="i == sectionData.prize.length - 1"
                          style="height: 32px; margin-left: 10px"
                          size="small"
                          icon="el-icon-plus"
                          type="primary"
                          @click="addPrize(prizeData, sectionData)"
                          :disabled="isEditDisalbed"
                          >添加</el-button
                        >
                      </div>
                    </div>
                  </template>
                </div>
                <div class="del-section">
                  <el-button
                    style="height: 32px; margin-left: 10px"
                    size="small"
                    type="danger"
                    icon="el-icon-delete"
                    @click="delSection(index)"
                    :disabled="isEditDisalbed"
                    >删除</el-button
                  >
                </div>
              </div></template
            >
          </div>
        </el-form>
      </el-col>
    </el-row>
    <!-- 提交 -->
    <div class="submit-wrap">
      <el-button @click="onCancel" class="award-remove_btn" size="medium"
        >取消</el-button
      >
      <el-button
        type="primary"
        class="award-remove_btn"
        size="medium"
        @click="onSubmit"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
import uploadSmallImg from '@common/uploadSmallImg' // 上传单个图片公共组件
import '@assets/css/quill.snow.css'
import { clearTagMixins } from '@/mixins/clearTag'
import {
  getActiveDetail,
  addActive,
  changeActive,
  getAalidationName
} from '@/api/activePull/adviserList/index'

export default {
  mixins: [clearTagMixins],
  data() {
    return {
      postId: '', //编辑or复制活动id
      activityDetailName: '', // 详情活动名称
      repeatName: '', // 活动名称是否重复
      activityInfo: {
        activityName: '', //名称
        activityStartTime: '', // 活动开始时间
        activityEndTime: '', // 活动结束时间
        acceptThePrizeStartTime: '', // 活动领取奖品起始时间
        acceptThePrizeEndTime: '', // 活动领取奖品结束时间
        activitySucceedStartTime: '', // 活动成单起始时间
        activitySucceedEndTime: '', // 活动成单结束时间
        enterAmountStartTime: '', // 活动入量起始时间
        enterAmountEndTime: '', // 活动入量结束时间
        activityConver: '', //活动封面
        activityPoster: '', //活动海报
        activityTime: [], // 活动时间
        acceptThePrizeTime: [], // 活动领取奖品时间
        activitySucceedTime: [], // 活动成单时间
        enterAmountTime: [], // 活动入量时间
        intakeChannelId: '', // 展翅入量渠道Id
        remark: '' //备注
      },
      activityInfoRules: {
        activityName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { max: 20, message: '长度不能大于20个字符', trigger: 'blur' }
        ],
        activityTime: [
          {
            required: true,
            message: '活动起始时间不能为空',
            trigger: 'blur'
          }
        ],
        acceptThePrizeTime: [
          {
            required: true,
            message: '领取奖品时间不能为空',
            trigger: 'blur'
          }
        ],
        enterAmountTime: [
          {
            required: true,
            message: '入量区间设置不能为空',
            trigger: 'blur'
          }
        ],
        activitySucceedTime: [
          {
            required: true,
            message: '成单区间设置不能为空',
            trigger: 'blur'
          }
        ],
        activityConver: [
          { required: true, message: '活动封面不能为空', trigger: 'blur' }
        ],
        activityPoster: [
          { required: true, message: '活动海报不能为空', trigger: 'blur' }
        ]
      },
      activityPrize: [
        {
          num: 0,
          minPersonNum: '',
          maxPersonNum: '',
          prize: [
            {
              num: 0,
              prizeName: '',
              prizeImg: '',
              prizeType: 'ENTITY'
            }
          ]
        }
      ],
      pickerOptions: {
        // selectableRange: (() => {
        //   let data = new Date()
        //   let hour = data.getHours()
        //   let minute = data.getMinutes()
        //   let second = data.getSeconds()
        //   return [`${hour}:${minute}:${second} - 23:59:59`]
        // })(),
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    }
  },
  components: {
    uploadSingImg,
    uploadSmallImg
  },
  computed: {
    showPrizeBtn() {
      return function(sectionData, i) {
        if (sectionData.prize.length === 1) {
          return true
        } else {
          if (i == 0) {
            return false
          } else {
            return true
          }
        }
      }
    },
    isEditDisalbed() {
      console.log(this.activityInfo.activityStatus)
      return (
        this.$route.query.type == 'edit' &&
        this.activityInfo.activityStatus === 'ONGOING'
      )
    }
  },
  created() {
    // 编辑or复制查询详情
    if (this.$route.query.type == 'edit' || this.$route.query.type == 'copy') {
      this.postId = this.$route.query.id
      this.searchActive()
    }
  },
  methods: {
    // 活动名称去重
    changeName(val) {
      if (this.activityDetailName === val || val.length === 0) return false
      getAalidationName(val, (res) => {
        this.repeatName = res
        if (res) {
          this.$message.error('活动名称重复!!!请重新填写或修改')
        }
      })
    },
    // 编辑一键复制回显
    searchActive() {
      getActiveDetail(this.postId, (res) => {
        if (res) {
          this.activityInfo = res
          this.activityDetailName = res.activityName
          this.$set(this, 'activityPrize', this.activityInfo.activityPrize)
          this.$set(this.activityInfo, 'activityTime', [
            res.activityStartTime,
            res.activityEndTime
          ])
          this.$set(this.activityInfo, 'acceptThePrizeTime', [
            res.acceptThePrizeStartTime,
            res.acceptThePrizeEndTime
          ])
          this.$set(this.activityInfo, 'enterAmountTime', [
            res.enterAmountStartTime,
            res.enterAmountEndTime
          ])
          this.$set(this.activityInfo, 'activitySucceedTime', [
            res.activitySucceedStartTime,
            res.activitySucceedEndTime
          ])
        }
      })
    },
    // 保存按钮
    onSubmit() {
      this.$refs['activityInfo'].validate((valid) => {
        if (!valid) {
          this.$message.warning('请检查必填项')
        } else {
          if (this.repeatName) {
            this.$message.error('活动名称重复!!!请重新填写或修改')
            return false
          } else if (
            this.activityInfo.acceptThePrizeStartTime <=
            this.activityInfo.activityEndTime
          ) {
            this.$message({
              message: '领取奖品时间应大于活动结束时间',
              type: 'warning'
            })
            return false
          } else if (
            this.activityInfo.enterAmountEndTime >
            this.activityInfo.activityEndTime
          ) {
            this.$message({
              message: '入量区间设置结束时间应小于等于活动结束时间',
              type: 'warning'
            })
            return false
          } else if (
            this.activityInfo.activitySucceedEndTime >
            this.activityInfo.activityEndTime
          ) {
            this.$message({
              message: '成单区间设置结束时间应小于等于活动结束时间',
              type: 'warning'
            })
            return false
          }
          // else if (
          //   this.activityInfo.activitySucceedStartTime <
          //     this.activityInfo.enterAmountStartTime ||
          //   this.activityInfo.activitySucceedEndTime >
          //     this.activityInfo.enterAmountEndTime
          // ) {
          //   this.$message({
          //     message: '成单时间设置应大于等于入量时间设置',
          //     type: 'warning'
          //   })
          //   return false
          // }
          let checkStatus = true
          let checkStatusArr = []
          let checkPrizeStatus = true
          let checkNumStatus = true
          let checkNumStatusArr = []
          this.activityPrize.forEach((element, index) => {
            // 人数档位区间不能为0
            checkStatus = this.checkSectionData(element, index, 'last')
            checkStatusArr.push(checkStatus)
            checkStatus = checkStatusArr.every(
              (e) => e === true || e === undefined
            )
            if (checkStatus === false) return false
            // 人数档位区间上层不能小于下层
            checkNumStatus = this.checkSectionDataNum(index)
            checkNumStatusArr.push(checkNumStatus)
            element.prize.forEach((ele) => {
              // 奖品名称/图片验证
              checkPrizeStatus = this.checkPrizeData(ele)
            })
          })
          checkNumStatus = checkNumStatusArr.every(
            (e) => e === true || e === undefined
          )
          if (checkNumStatus === false) return false
          if (checkStatus === false) return false
          if (checkPrizeStatus === false) return false
          let obj = Object.assign({}, this.activityInfo, {
            activityPrize: this.activityPrize
          })
          if (!this.postId || this.postId === '') {
            // 新增
            addActive(
              obj,
              (res) => {
                this.clearTag()
              },
              (err) => {
                this.$message({
                  message: err.message,
                  type: 'warning'
                })
              }
            )
          } else {
            // 复制
            if (this.$route.query.type == 'copy') {
              // 新增
              addActive(
                obj,
                (res) => {
                  this.clearTag()
                },
                (err) => {
                  this.$message({
                    message: err.message,
                    type: 'warning'
                  })
                }
              )
            } else {
              // 编辑
              changeActive(
                this.postId,
                obj,
                (res) => {
                  this.clearTag()
                },
                (err) => {
                  this.$message({
                    message: err.message,
                    type: 'warning'
                  })
                }
              )
            }
          }
        }
      })
    },
    // 取消按钮
    onCancel() {
      this.clearTag()
    },
    signOut() {
      this.$router.go(-1)
    },
    getActivePoster(url) {
      this.$nextTick(() => {
        this.activityInfo.activityPoster = url
      })
    },
    getActivityConver(url) {
      this.$set(this.activityInfo, 'activityConver', url)
    },
    getPrizePoster(data) {
      let { index, i, url } = data
      this.$nextTick(() => {
        this.activityPrize[index].prize[i].prizeImg = url
      })
    },
    checkPrizeData(prizeData) {
      if (!prizeData.prizeName) {
        this.$message({
          message: '请输入奖品名称',
          type: 'warning'
        })
        return false
      } else if (prizeData.prizeName.length > 8) {
        this.$message({
          message: '奖品名称最多输入八个字符',
          type: 'warning'
        })
        return false
      } else if (!prizeData.prizeImg) {
        this.$message({
          message: '请上传奖品图片',
          type: 'warning'
        })
        return false
      }
    },
    checkSectionData(sectionData, index, last) {
      // 下标和数组长度一致&&是点击保存按钮
      if (last && this.activityPrize.length - 1 === sectionData.num) {
        let status = true
        status = this.checkLastNum(sectionData, index, last)
        return status
      }
      if (
        sectionData.minPersonNum == 0 ||
        sectionData.minPersonNum == null ||
        sectionData.maxPersonNum == 0 ||
        sectionData.maxPersonNum == null
      ) {
        this.$message({
          message: '人数档位区间不能为0',
          type: 'warning'
        })
        return false
      } else if (sectionData.maxPersonNum <= sectionData.minPersonNum) {
        this.$message({
          message: '人数档位区间开始区间不能大于结束区间',
          type: 'warning'
        })
        return false
      }
    },
    checkLastNum(sectionData) {
      if (sectionData.minPersonNum == 0 || sectionData.minPersonNum == null) {
        this.$message({
          message: '人数档位区间不能为0',
          type: 'warning'
        })
        return false
      } else if (
        sectionData.minPersonNum > 0 &&
        sectionData.maxPersonNum > 0 &&
        sectionData.maxPersonNum <= sectionData.minPersonNum
      ) {
        this.$message({
          message: '人数档位区间开始区间不能大于结束区间',
          type: 'warning'
        })
        return false
      }
    },
    // 判断下一区间不能小于上一区间
    checkSectionDataNum(index) {
      // 区间1不需要判断
      if (index == 0) return true
      if (this.activityPrize[index]) {
        // 如果下个区间开始阶段大于上个区间结束阶段
        if (
          this.activityPrize[index].minPersonNum <=
          this.activityPrize[index - 1].maxPersonNum
        ) {
          this.$message({
            message: '人数档位区间需大于上次档位区间',
            type: 'warning'
          })
          return false
        }
      }
    },
    // 新增梯队区间
    addSection() {
      if (this.activityPrize.length) {
        if (this.activityPrize.length == 5) {
          this.$message({
            message: '最多添加五条档位',
            type: 'warning'
          })
          return false
        }
        let checkStatus = true
        let checkPrizeStatus = true
        let checkNumStatus = true
        // 人数档位区间不能为0
        this.activityPrize.forEach((element, index) => {
          checkStatus = this.checkSectionData(element)
        })
        if (checkStatus === false) return false
        // 人数档位区间上层不能小于下层
        this.activityPrize.forEach((element, index) => {
          checkNumStatus = this.checkSectionDataNum(index)
        })
        if (checkNumStatus === false) return false
        // 奖品名称/图片验证
        this.activityPrize[this.activityPrize.length - 1].prize.forEach(
          (element) => {
            checkPrizeStatus = this.checkPrizeData(element)
          }
        )
        if (checkPrizeStatus === false) return false
      }
      this.activityPrize.push({
        num: this.activityPrize.length,
        minPersonNum: '',
        maxPersonNum: '',
        prize: [
          {
            num: 0,
            prizeName: '',
            prizeImg: '',
            prizeType: 'ENTITY'
          }
        ]
      })
    },
    // 删除梯队区间
    delSection(index) {
      this.activityPrize.splice(index, 1)
    },
    // 新增单个奖励
    addPrize(prizeData, sectionData) {
      console.log(prizeData, sectionData)
      let checkStatus = this.checkPrizeData(prizeData)
      if (checkStatus === false) return false
      if (sectionData.prize.length == 6) {
        this.$message({
          message: '档位下最多添加六条礼品数',
          type: 'warning'
        })
        return false
      }
      this.activityPrize.forEach((element, index) => {
        if (sectionData.num === element.num) {
          // 找到当前梯队id 插入奖励
          this.activityPrize[index].prize.push({
            num: element.prize.length, // 下标为当前梯队下的奖励数组的长度
            prizeName: '',
            prizeImg: '',
            prizeType: 'ENTITY'
          })
        }
      })
    },
    // 删除单个奖励
    delPrize(index, i) {
      this.activityPrize[index].prize.splice(i, 1)
    }
  },
  watch: {
    'activityInfo.activityTime': {
      handler(newV, oldV) {
        if (newV == null) {
          this.activityInfo.activityStartTime = ''
          this.activityInfo.activityEndTime = ''
        } else {
          this.activityInfo.activityStartTime = newV[0]
          this.activityInfo.activityEndTime = newV[1]
        }
        console.log(
          this.activityInfo.activityStartTime,
          this.activityInfo.activityEndTime
        )
      },
      immediate: true,
      deep: true
    },
    'activityInfo.acceptThePrizeTime': {
      handler(newV, oldV) {
        if (newV == null) {
          this.activityInfo.acceptThePrizeStartTime = ''
          this.activityInfo.acceptThePrizeEndTime = ''
        } else {
          this.activityInfo.acceptThePrizeStartTime = newV[0]
          this.activityInfo.acceptThePrizeEndTime = newV[1]
        }
      },
      immediate: true,
      deep: true
    },
    'activityInfo.activitySucceedTime': {
      handler(newV, oldV) {
        if (newV == null) {
          this.activityInfo.activitySucceedStartTime = ''
          this.activityInfo.activitySucceedEndTime = ''
        } else {
          this.activityInfo.activitySucceedStartTime = newV[0]
          this.activityInfo.activitySucceedEndTime = newV[1]
        }
      },
      immediate: true,
      deep: true
    },
    'activityInfo.enterAmountTime': {
      handler(newV, oldV) {
        if (newV == null) {
          this.activityInfo.enterAmountStartTime = ''
          this.activityInfo.enterAmountEndTime = ''
        } else {
          this.activityInfo.enterAmountStartTime = newV[0]
          this.activityInfo.enterAmountEndTime = newV[1]
        }
      },
      immediate: true,
      deep: true
    }
  }
}
</script>
<style lang="less" scoped>
:deep(.el-input__inner) {
  height: 32px;
}
.limit {
  height: 30px;
  line-height: 30px;
  text-align: right;
  margin: 20px 0 10px;
  padding-right: 10px;
  span {
    color: #f00;
  }
}
.activity-input {
  width: 500px;
}
.section-prize {
  margin-left: 80px;
  .section-header {
    display: flex;
    margin: 30px 0 10px;
    font-size: 15px;
    font-weight: 600;
    > div {
      text-align: center;
      margin-left: 30px;
    }
    .prize-pic {
      margin-left: 10px;
    }
  }
  .section-index {
    margin-left: 0 !important;
  }
  .section-wrap {
    display: flex;
    align-content: center;
    > div {
      text-align: center;
      margin-left: 30px;
    }
  }
  .section-num {
    width: 150px;
    .num-input {
      width: 60px;
    }
  }
  .prize-wrap {
    display: flex;
    margin-bottom: 30px;
  }
  .prize-pic {
    width: 200px;
  }
  .prize-name {
    width: 150px;
  }
}
.submit-wrap {
  margin: 20px 20px 30px 550px;
}
</style>
